using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace FoundationLib.AddIns.Constraints
{
	/// <summary>
	/// Provides an abstract implementation for visitors using regular expression
	/// string replacement
	/// </summary>
	public abstract class RegexVisitor : IVisitor
	{
		/// <summary>
		/// The regular expression pattern
		/// </summary>
		private string pattern;

		/// <summary>
		/// Creates a new regular expression visitor
		/// </summary>
		/// <param name="pattern">The regular expression pattern to use</param>
		protected RegexVisitor(string pattern)
		{
			if (pattern == null)
				throw new ArgumentNullException("pattern");
			this.pattern = pattern;
		}

		/// <summary>
		/// Evaluates and replaces the matching regular expression group
		/// </summary>
		/// <returns>The string after evaluation and replacement</returns>
		/// <param name="match">The match</param>
		protected abstract string Evaluate(Match match);

		/// <summary>
		/// Visits the element
		/// </summary>
		/// <param name="statement">The element to visit</param>
		public void Visit(IVisitable statement)
		{
			if (statement == null || String.IsNullOrEmpty(statement.Value))
				return;

			string result = statement.Value.Trim();

			Regex regex = new Regex(this.pattern);
			result = regex.Replace(result, new MatchEvaluator(this.Evaluate));

			statement.Value = result;
		}
	}
}
